﻿using gregn6Lib;
using grdes6Lib;
using Newtonsoft.Json.Linq;
using ReportMealManagementSystem.Business;
using ReportMealManagementSystem.Entity;
using ReportMealManagementSystem.Tool;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ReportMealManagementSystem
{
    /// <summary>
    /// AllMealStatisticsReportOneDay.xaml 的交互逻辑
    /// </summary>
    public partial class AllMealStatisticsReportOneDay : UserControl
    {
        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        int districtID = int.Parse(ConfigurationManager.AppSettings["districtID"]);
        BasicInfo basicInfo = new BasicInfo();
        int pageIndex = 1;
        int pageSize = 50;
        int totalNumber = 0;
        int totalPage = 0;
        ObservableCollection<object> observableCollection = null;
        State state = State.None;
        JObject joItem = new JObject();
        JObject joParam = new JObject();
        ValueVerify valueVerify = new ValueVerify();
        ExcelOperate excelOperate = new ExcelOperate();
        string folder = "";
        string fileName = "";

        JArray jaPrintData = new JArray();
        private GridppReport Report = new GridppReport();
        private GRDesigner ReportDesigener = new GRDesigner();

        public AllMealStatisticsReportOneDay()
        {
            InitializeComponent();
        }

        private void GetDiningHallInfo()
        {
            string msg = "";
            JObject joDiningHallParam = new JObject();
            joDiningHallParam["PageIndex"] = 1;
            joDiningHallParam["PageSize"] = 1000;
            joDiningHallParam["DistrictID"] = districtID;
            int totalNumber = 0;
            int totalPage = 0;
            var DistrictList = basicInfo.GetData(joDiningHallParam, "gbt/BasicInfo/DiningHallInfo/", "食堂", ref totalNumber, ref totalPage, ref msg);
            if (DistrictList != null)
            {
                JObject joItem = new JObject();
                List<SelectedItem> selectedItems = new List<SelectedItem>();
                selectedItems.Add(new SelectedItem
                {
                    ID = null,
                    Name = ""
                });
                for (int index = 0; index < DistrictList.Count; index++)
                {
                    joItem = (JObject)DistrictList[index];
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)DistrictList[index]["hallId"],
                        Name = (string)DistrictList[index]["hallName"]
                    });
                }

                cbHallName.Dispatcher.Invoke(new Action(delegate
                {
                    cbHallName.ItemsSource = selectedItems;
                    cbHallName.SelectedIndex = 0;
                }));
            }
        }

        private void GetMealTimeInfo()
        {
            string msg = "";
            JObject joMealTimeParam = new JObject();
            joMealTimeParam["PageIndex"] = 1;
            joMealTimeParam["PageSize"] = 1000;
            joMealTimeParam["DistrictID"] = districtID;
            var MealTimeList = basicInfo.GetData(joMealTimeParam, "gbt/BasicInfo/MealTimeInfo/", "餐点", ref totalNumber, ref totalPage, ref msg);
            if (MealTimeList != null)
            {
                JObject joItem = new JObject();
                List<SelectedItem> selectedItems = new List<SelectedItem>();
                selectedItems.Add(new SelectedItem
                {
                    ID = null,
                    Name = ""
                });
                for (int index = 0; index < MealTimeList.Count; index++)
                {
                    joItem = (JObject)MealTimeList[index];
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)MealTimeList[index]["mealId"],
                        Name = (string)MealTimeList[index]["mealName"]
                    });
                }

                cbMealName.Dispatcher.Invoke(new Action(delegate
                {
                    cbMealName.ItemsSource = selectedItems;
                    cbMealName.SelectedIndex = 0;
                }));
            }
        }

        private void GetDistrictInfo()
        {
            string msg = "";
            JObject joCompanyParam = new JObject();
            joCompanyParam["PageIndex"] = 1;
            joCompanyParam["PageSize"] = 1000;
            joCompanyParam["DistrictID"] = districtID;
            int totalNumber = 0;
            int totalPage = 0;
            var DistrictList = basicInfo.GetData(joCompanyParam, "gbt/BasicInfo/DistrictList/", "区域", ref totalNumber, ref totalPage, ref msg);
            if (DistrictList != null)
            {
                JObject joItem = new JObject();
                List<SelectedItem> selectedItems = new List<SelectedItem>();
                for (int index = 0; index < DistrictList.Count; index++)
                {
                    joItem = (JObject)DistrictList[index];
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)DistrictList[index]["districtID"],
                        Name = (string)DistrictList[index]["districtName"]
                    });
                }

                cbDistrictName.Dispatcher.Invoke(new Action(delegate
                {
                    cbDistrictName.ItemsSource = selectedItems;
                    cbDistrictName.SelectedIndex = 0;
                }));
            }
        }

        private void GetAllMealStatisticsReportInfo()
        {
            string msg = "";
            var DataList = basicInfo.GetData(joParam, "gbt/Meal/AllMealStatisticsReportInfo/", "报餐统计", ref totalNumber, ref totalPage, ref msg);
            if (DataList != null)
            {
                JObject joItem = new JObject();
                observableCollection = new ObservableCollection<object>();
                for (int index = 0; index < DataList.Count; index++)
                {
                    joItem = (JObject)DataList[index];
                    observableCollection.Add(new
                    {
                        HallNumber = (string)joItem["hallNumber"],
                        HallName = (string)joItem["hallName"],
                        MealNumber = (string)joItem["mealNumber"],
                        MealName = (string)joItem["mealName"],
                        qty = (string)joItem["qty"],
                        date = string.IsNullOrWhiteSpace((string)joItem["date"]) ? "" : ((DateTime)joItem["date"]).ToString("yyyy-MM-dd"),
                        DistrictNumber = (string)joItem["districtNumber"],
                        DistrictName = (string)joItem["districtName"],
                    });
                }

                lvDate.Dispatcher.Invoke(new Action(delegate
                {
                    lvDate.ItemsSource = observableCollection;
                    message.Content = msg;
                }));
            }
        }

        private void GetAllMealStatisticsReportInfoExport()
        {
            string msg = "";
            joParam["PageSize"] = 1000000;
            var DataList = basicInfo.GetData(joParam, "gbt/Meal/AllMealStatisticsReportInfo/", "报餐统计", ref totalNumber, ref totalPage, ref msg);
            System.Data.DataTable dt = new System.Data.DataTable();
            if (DataList != null && DataList.Count > 0)
            {
                dt.Columns.Add("餐点编码");
                dt.Columns.Add("餐点名称");
                dt.Columns.Add("份数");
                dt.Columns.Add("就餐日期");
                dt.Columns.Add("食堂编码");
                dt.Columns.Add("食堂名称");
                dt.Columns.Add("区域编码");
                dt.Columns.Add("区域名称");
                for (int index = 0; index < DataList.Count; index++)
                {
                    joItem = (JObject)DataList[index];
                    dt.Rows.Add((string)joItem["mealNumber"], (string)joItem["mealName"], (string)joItem["qty"], string.IsNullOrWhiteSpace((string)joItem["date"]) ? "" : ((DateTime)joItem["date"]).ToString("yyyy-MM-dd"),
                        (string)joItem["hallNumber"], (string)joItem["hallName"], (string)joItem["districtNumber"], (string)joItem["districtName"]);
                }

                excelOperate.ExportExcel(dt, folder, fileName, new string[0], ref msg);
                this.message.Dispatcher.Invoke(new Action(delegate {
                    message.Content = msg;
                }));
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            joParam = new JObject();
            joParam["DistrictID"] = districtID;
            joParam["PageIndex"] = pageIndex;
            joParam["PageSize"] = pageSize;
            joParam["startTime"] = DateTime.Now.Date;
            joParam["endTime"] = DateTime.Now.Date;
            dpDate.SelectedDate = DateTime.Now.Date;
            Task task = new Task(new Action(delegate
            {
                GetDiningHallInfo();
                GetMealTimeInfo();
                GetDistrictInfo();
                GetAllMealStatisticsReportInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            if (state == State.None)
            {
                bData.Visibility = Visibility.Visible;
                lvDate.IsEnabled = false;
                state = State.Search;
                lblTitle.Content = "查询";
            }
            else if (state == State.Search)
            {
                _loading.Visibility = Visibility.Visible;
                bData.Visibility = Visibility.Collapsed;
                lvDate.IsEnabled = true;
                int hallID = 0;
                int mealID = 0;
                if (cbHallName.SelectedValue != null)
                {
                    hallID = (int)cbHallName.SelectedValue;
                }
                if (cbMealName.SelectedValue != null)
                {
                    mealID = (int)cbMealName.SelectedValue;
                }
                DateTime? date = null;
                if (dpDate.SelectedDate != null)
                {
                    date = dpDate.SelectedDate;
                }
                txtPageIndex.Text = "1";
                Task task = new Task(new Action(delegate
                {
                    pageIndex = 1;
                    joParam = new JObject();
                    joParam["PageIndex"] = pageIndex;
                    joParam["PageSize"] = pageSize;
                    if (hallID != 0)
                    {
                        joParam["HallID"] = hallID;
                    }
                    if (mealID != 0)
                    {
                        joParam["MealID"] = mealID;
                    }
                    if (date != null)
                    {
                        joParam["startTime"] = date;
                        joParam["endTime"] = date;
                    }
                    joParam["DistrictID"] = districtID;
                    GetAllMealStatisticsReportInfo();
                }));
                task.Start();
                task.ContinueWith((t) =>
                {
                    _loading.Dispatcher.Invoke(new Action(delegate
                    {
                        _loading.Visibility = Visibility.Collapsed;
                        lvDate.IsEnabled = true;
                    }));
                    state = State.None;
                });
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            state = State.None;
            bData.Visibility = Visibility.Collapsed;
            lvDate.IsEnabled = true;

            cbMealName.SelectedValue = null;
            cbHallName.SelectedValue = null;
        }

        private void Export_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
            sfd.Filter = "Excel|*.xlsx";
            //调用ShowDialog()方法显示该对话框，该方法的返回值代表用户是否点击了确定按钮
            if (sfd.ShowDialog() == true)
            {
                folder = System.IO.Path.GetDirectoryName(sfd.FileName);
                fileName = System.IO.Path.GetFileName(sfd.FileName);
                _loading.Visibility = Visibility.Visible;
                Task task = new Task(new Action(delegate {
                    GetAllMealStatisticsReportInfoExport();
                }));
                task.Start();
                task.ContinueWith((t) =>
                {
                    _loading.Dispatcher.Invoke(new Action(delegate {
                        _loading.Visibility = Visibility.Collapsed;
                    }));
                });
            }
        }

        private void ReportFetchRecord()
        {
            try
            {
                if (jaPrintData.Count > 0)
                {
                    string date = "";
                    for (int mealReportIndex = 0; mealReportIndex < jaPrintData.Count; mealReportIndex++)
                    {
                        date = string.IsNullOrEmpty((string)jaPrintData[mealReportIndex]["date"]) ? "" : ((DateTime)jaPrintData[mealReportIndex]["date"]).ToString("yyyy-MM-dd");
                        Report.DetailGrid.Recordset.Append();
                        Report.FieldByName("hallName").AsString = jaPrintData[mealReportIndex]["hallName"].ToString();
                        Report.FieldByName("mealName").AsString = jaPrintData[mealReportIndex]["mealName"].ToString();
                        Report.FieldByName("qty").AsString = jaPrintData[mealReportIndex]["qty"].ToString();
                        Report.FieldByName("unit").AsString = "份";
                        Report.FieldByName("date").AsString = date;
                        Report.DetailGrid.Recordset.Post();
                    }
                }

                message.Content = "正在加载打印数据···";
            }
            catch (Exception ex)
            {
                message.Content = ex.Message;
            }
        }

        private void PrintPreview()
        {
            try
            {
                string msg = "";
                string date = dpDate.SelectedDate.ToString();
                string hallName = "";
                string path = "";
                if (!string.IsNullOrEmpty(cbHallName.Text.Trim()))
                {
                    hallName = cbHallName.Text.Trim();
                    path = @"PringTemplate\OneDayStatistics.grf";
                }
                else
                {
                    path = @"PringTemplate\AllStatistics.grf";
                }
                _loading.Visibility = Visibility.Visible;
                Task task = new Task(new Action(delegate
                {
                    joParam["PageSize"] = 1000000;
                    jaPrintData = new JArray();
                    jaPrintData = basicInfo.GetData(joParam, "gbt/Meal/AllMealStatisticsReportInfo/", "报餐统计", ref totalNumber, ref totalPage, ref msg);
                }));
                task.Start();
                task.ContinueWith((t) =>
                {
                    _loading.Dispatcher.Invoke(new Action(delegate
                    {
                        Report.LoadFromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + path);
                        Report.FetchRecord -= new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                        Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);

                        Report.ParameterByName("hallName").AsString = hallName;
                        Report.ParameterByName("date").AsString = date;
                        Report.PrintPreview(true);
                        _loading.Visibility = Visibility.Collapsed;
                        message.Content = "就绪";
                    }));
                });
            }
            catch (Exception ex)
            {
                message.Content = ex.Message;
            }
        }

        private void Print()
        {
            try
            {
                string msg = "";
                string date = dpDate.SelectedDate.ToString();
                string hallName = "";
                string path = "";
                if (!string.IsNullOrEmpty(cbHallName.Text.Trim()))
                {
                    hallName = cbHallName.Text.Trim();
                    path = @"PringTemplate\OneDayStatistics.grf";
                }
                else
                {
                    path = @"PringTemplate\AllStatistics.grf";
                }
                _loading.Visibility = Visibility.Visible;
                Task task = new Task(new Action(delegate
                {
                    joParam["PageSize"] = 1000000;
                    jaPrintData = new JArray();
                    jaPrintData = basicInfo.GetData(joParam, "gbt/Meal/AllMealStatisticsReportInfo/", "报餐统计", ref totalNumber, ref totalPage, ref msg);
                }));
                task.Start();
                task.ContinueWith((t) =>
                {
                    _loading.Dispatcher.Invoke(new Action(delegate
                    {
                        Report.LoadFromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + path);
                        Report.FetchRecord -= new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                        Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);

                        Report.ParameterByName("hallName").AsString = hallName;
                        Report.ParameterByName("date").AsString = date;
                        Report.Print(true);
                        _loading.Visibility = Visibility.Collapsed;
                        message.Content = "就绪";
                    }));
                });
            }
            catch (Exception ex)
            {
                message.Content = ex.Message;
            }
        }

        private void Print_Click(object sender, RoutedEventArgs e)
        {
            Print();
        }

        private void PrintPreview_Click(object sender, RoutedEventArgs e)
        {
            PrintPreview();
        }

        private void lvData_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            state = State.None;
            bData.Visibility = Visibility.Collapsed;
            lvDate.IsEnabled = true;

            cbMealName.SelectedValue = null;
            cbHallName.SelectedValue = null;
        }

        private void btnFirstPage_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            txtPageIndex.Text = "1";
            Task task = new Task(new Action(delegate
            {
                pageIndex = 1;
                joParam["PageIndex"] = pageIndex;
                GetAllMealStatisticsReportInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnPageUp_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate
            {
                if (pageIndex > 1)
                {
                    pageIndex--;
                    txtPageIndex.Dispatcher.Invoke(new Action(delegate
                    {
                        txtPageIndex.Text = pageIndex.ToString();
                    }));
                    joParam["PageIndex"] = pageIndex;
                    GetAllMealStatisticsReportInfo();
                }
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnSkip_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            if (!string.IsNullOrEmpty(txtPageIndex.Text.Trim()) && valueVerify.IsNumber(txtPageIndex.Text.Trim()))
            {
                pageIndex = int.Parse(txtPageIndex.Text.Trim());
                if (pageIndex == 0)
                {
                    pageIndex = 1;
                    txtPageIndex.Text = "1";
                }
                else if (pageIndex == totalPage)
                {
                    pageIndex = totalPage;
                    txtPageIndex.Text = totalPage.ToString();
                }
            }
            Task task = new Task(new Action(delegate
            {
                joParam["PageIndex"] = pageIndex;
                GetAllMealStatisticsReportInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnNextPage_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate
            {
                if (pageIndex < totalPage)
                {
                    pageIndex++;
                    txtPageIndex.Dispatcher.Invoke(new Action(delegate
                    {
                        txtPageIndex.Text = pageIndex.ToString();
                    }));
                    joParam["PageIndex"] = pageIndex;
                    GetAllMealStatisticsReportInfo();
                }
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnEndPage_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate
            {
                if (totalPage > 0)
                {
                    pageIndex = totalPage;
                }
                else
                {
                    pageIndex = 1;
                }
                txtPageIndex.Dispatcher.Invoke(new Action(delegate
                {
                    txtPageIndex.Text = pageIndex.ToString();
                }));
                joParam["PageIndex"] = pageIndex;
                GetAllMealStatisticsReportInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }
    }
}
